var express = require('express');
var login_router = express.Router();
let Students = require("../mongodb/mongodb").Students //引入数据库模型
let Teachers = require("../mongodb/mongodb").Teachers //引入数据库模型
let DB;
var md5 = require("md5-node") //引入md5
let nodeMail = require("../email/email")//引入封装好的nodeMail
const SMSClient = require('@alicloud/sms-sdk') //阿里云短信服务
// 处理post请求的中间件，用于解析post返回的数据
// const bodyParser = require('body-parser')
// login_router.use(bodyParser.urlencoded({
//   extended: false
// }))

// home_router.use(express.json())

/* login验证. */
login_router.post('/', function (req, res, next) {
  let nowTime = new Date().getTime();
  // 判断验证码是否失效
  if(nowTime-getCodeTime>=5*1000*60){
    res.send({
      count,
      status: 300,
      msg: '验证码失效'
    })
  }else{
  let user = req.body.username;
  let pass = req.body.password;
  let myStatus = req.body.myStatus;//获取身份（学生或者是老师）
 
  if(myStatus=='Students'){DB = Students}else{DB = Teachers}
  DB.where({
    user: user,
    pass:pass
  }).countDocuments(function (err, count) {
    if (err) {
      return handleError(err)
    } else if (count == 1) {
      res.send({
        count,
        status: 200,
        msg: '登录成功！'
      })
      console.log("登陆成功")
    } else {
      console.log("账号或密码错误")
      res.send({
        count,
        status: 400,
        msg: '账号或密码错误！'
      })
    }
  })
  }
  
});


/* 注册验证.mongoose增加数据要用数据库model实例 */
login_router.post('/register', function (req, res, next) {
  let nowTime = new Date().getTime();
  // 判断验证码是否失效
  if(nowTime-getCodeTime>=5*1000*60){
    res.send({
      count,
      status: 300,
      msg: '验证码失效'
    })
  }else{
  let user = req.body.username;
  let pass = req.body.password;
  let myStatus = req.body.myStatus;//获取身份（学生或者是老师）
  if(myStatus=='Students'){DB = Students}else{DB = Teachers}
DB.where({
    user: user,
    pass: pass
  }).countDocuments(function (err, count) {
    if (err) {
      return handleError(err)
    } else if (count == 1) {
      res.send({
        count,
        status: 200,
        msg: '此账号已注册！'
      })
      console.log("已注册")
    } 
  }).exec(()=>{
    let s_or_t;
    if(myStatus=='Students')
    {
      s_or_t = new Students({
        user:user,
        pass:pass,
        student:'',
        avatar:'',
        sex:'',
        subject_good:'',
      });
    }else{
      s_or_t = new Teachers({
        user:user,
        pass:pass,
        teacher:'',
        avatar:'',
        sex:'',
        subject_good:'',
        school_name:'',
      });
    }
     
    s_or_t.save((err)=>{
      if(err){console.log(err)}
      else{
        console.log("注册成功！");
        res.send({
          status:200,
          msg:'注册成功，点击login完成登录！'
        })
      }
    })
  })
  }
  
});

/* 修改密码. */
login_router.post('/alter', function (req, res, next) {
  let nowTime = new Date().getTime();
  // 判断验证码是否失效
  if(nowTime-getCodeTime>=5*1000*60){
    res.send({
      status: 300,
      msg: '验证码失效'
    })
  }else{
  let user = req.body.username;
  let pass = req.body.password;
  let myStatus = req.body.myStatus;//获取身份（学生或者是老师）
  if(myStatus=='Students'){DB = Students}else{DB = Teachers}
  let modify;
  // 第一个参数为条件，第二个是要修改的值，第三个是回调函数
DB.updateOne({user:user},{pass:pass},(err,doc)=>{
    if(err){console.log(err);console.log("修改密码失败"); return}
    else{
      console.log(doc);
      modify = doc.nModified  
      console.log('修改成功！');
      console.log('modify='+modify==0)
      console.log('modify='+modify==1)
      console.log('type='+typeof(doc.nModified))
      console.log('type='+typeof(modify))
      console.log('type='+modify)
    }
  }).exec(()=>{
    if(modify==1){
      console.log('modify='+modify)
      res.send({
        status:200,
        msg:'已修改，点击login完成登录！'
      })
    }else{
      console.log('modify='+modify)
      res.send({
        status:300,
        msg:'已修改，点击login完成登录！'
      })
    }
  })
 
  } 
});

module.exports = login_router;


// 定义获取验证码时间
let getCodeTime;
// AccessKey ID：
// LTAI4GKy4HQvaGHxasP4qgvi
// AccessKey Secret：
// 38vLKn4mA9frlWkJ9DSnlc9X22AFma
//随机验证码
function createVerifyCode() {
  var Num = "";
  for (var i = 0; i < 4; i++) {
    Num += Math.floor(Math.random() * 10);
  }
  return Num;
}
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = 'yourAccessKeyId'
const secretAccessKey = 'yourAccessKeySecret'

//初始化sms_client
let smsClient = new SMSClient({
  accessKeyId,
  secretAccessKey
})

function ToPhoneOrEmail(req){
  let code = createVerifyCode() //生成验证码
  let regPhone = /^1\d{10}$/
  // 如果采用手机登录的，那就发验证码给手机
  if (regPhone.test(req.body.user)) {
    let PhoneNumbers = req.body.user;
    //发送手机验证码
    smsClient.sendSMS({
      PhoneNumbers: PhoneNumbers, //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为：国际区号+号码，如“85200000000”
      SignName: '云通信产品', //必填:短信签名-可在短信控制台中找到
      TemplateCode: 'SMS_1000000', //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
      TemplateParam: '{"code":code}' //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时。
    }).then(function (res) {
      let {
        Code
      } = res
      if (Code === 'OK') {
        //处理返回参数
        console.log(res);
        // 发送验证码成功，则开始计时
        getCodeTime = new Date().getTime()
      }
    }, function (err) {
      console.log(err);
      return 0;
    })
  }else{
    let email = '1502039268@qq.com'
    //如果是邮箱登录的那就发给邮箱
    var mail = {
      // 发件人
      from: '<15917954121@163.com>',
      // 主题
      subject: 'weteach verifyCode',//邮箱主题
      // 收件人
      to: email,//前台传过来的邮箱
      // 邮件内容，HTML格式
      // text: '用' + code + '作为你的验证码'//发送验证码
      html: `
      <p>Hello！</p>
      <p>Welcome to use our products [weteach]</p>
      <p>author："hmy"</p>
      <p>your dynamic code is：<strong style="color: #ff4e2a;">${code}</strong></p>
      <p>*** The verification code is valid within 5 minutes ***</p>` // html 内容
  };
  nodeMail(mail);
  // 发送验证码成功则开始计时
  getCodeTime = new Date().getTime()
  }

  // 发送验证码给前台保存，以备验证用户输入的验证码
  let verifyCode = md5(code)
  return verifyCode
}
// 验证码模块
login_router.post('/getCode', function (req, res, next) {
  
  let verifyCode = ToPhoneOrEmail(req)
  res.send({
    verifyCode: verifyCode
  })
})